import { Component, OnInit, TemplateRef, SecurityContext } from '@angular/core';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
import { BsModalService } from 'ngx-bootstrap/modal';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { FormGroup, FormControl } from '@angular/forms';

import { TypeaheadMatch } from 'ngx-bootstrap/typeahead/typeahead-match.class';
import { DomSanitizer } from '@angular/platform-browser';
import { Technologiy } from 'src/app/model/technology';
import { User } from 'src/app/model/user';
import { MessageService } from 'src/app/service/message.service';
import { MentorSkills } from 'src/app/model/mentorskills';
import { MentorCalendar } from 'src/app/model/mentorcalendar';

@Component({
  selector: 'app-editskills',
  templateUrl: './editskills.component.html',
  styleUrls: ['./editskills.component.css']
})
export class EditskillsComponent implements OnInit {

  headers = new HttpHeaders({ 'Content-Type': 'application/json' });

  modalRef: BsModalRef

  action: string = 'saved'
  skills: string = ''
  skillsArray: string[] = []
  skillsForm = new FormGroup({
    skills: new FormControl('')
  })
  alerts: any = []
  response: any
  user: User
  mentorSkills: MentorSkills
  deleteId: number

  calendarId: number
  minDate: Date = new Date()
  maxDate: Date = new Date()
  bsRangeValue: Date[]

  constructor(private http: HttpClient,
    private modalService: BsModalService,
    private messageService: MessageService,
    sanitizer: DomSanitizer) {

    this.alerts = this.alerts.map((alert: any) => ({
      type: alert.type,
      msg: sanitizer.sanitize(SecurityContext.HTML, alert.msg)
    }))

    this.user = JSON.parse(localStorage.getItem('userinfo'))

    this.http.get('/api/skills/findByMentorId/' + this.user.id)
      .subscribe((data: any) => {
        console.log('/api/skills/findByMentorId/', data)
        this.response = data;
        this.response.forEach(element => {
          this.selectedOptions.push(element);
        })
        console.log('this.selectedOptions', this.selectedOptions)
      })

    this.http.get('/api/calendar/findByMentorId/' + this.user.id)
      .subscribe((data: any) => {
        console.log('/api/calendar/findByMentorId/', data)
        if (data.id != null) {
          this.calendarId = data.id

          // this.minDate = new Date(data.startDate)
          this.minDate.setDate(this.minDate.getDate());
          this.maxDate.setDate(this.minDate.getDate() + 365);
          this.bsRangeValue = [new Date(data.startDate), new Date(data.endDate)]
          console.log('1this.bsRangeValue', this.bsRangeValue)
        } else {
          this.minDate = new Date()
          let bsValue: Date = new Date()
          bsValue.setDate(this.minDate.getDate() + 7)
          this.maxDate = new Date()
          this.minDate.setDate(this.minDate.getDate())
          this.maxDate.setDate(this.minDate.getDate() + 365)
          this.bsRangeValue = [this.minDate, bsValue]
          console.log('2this.bsRangeValue', this.bsRangeValue)
        }
      })

    this.http.get('/api/technologies')
      .subscribe((data: any) => {
        console.log('/api/technologies', data)
        this.response = data;
        this.response.forEach(element => {
          this.technologies.push(element);
        })
        console.log('this.technologies', this.technologies)
      })
  }

  ngOnInit(): void {
  }

  format = function (t, format) {
    // var t = new Date(time);
    var tf = function (i) { return (i < 10 ? '0' : '') + i };
    return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
      switch (a) {
        case 'yyyy':
          return tf(t.getUTCFullYear());
          break;
        case 'MM':
          return tf(t.getUTCMonth() + 1); // 返回 用世界时表示时的月份，该值是 0（一月） ~ 11（十二月） 之间中的一个整数。所以要加1
          break;
        case 'mm':
          return tf(t.getUTCMinutes());
          break;
        case 'dd':
          return tf(t.getUTCDate());
          break;
        case 'HH':
          return tf(t.getUTCHours());
          break;
        case 'ss':
          return tf(t.getUTCSeconds());
          break;
      };
    });
  };
  // alert(format(1396178344662, 'yyyy-MM-dd HH:mm:ss'));
  saveDate(): any {
    console.log('saveDate - this.bsRangeValue', this.bsRangeValue)
    let mentorCalendar: MentorCalendar = new MentorCalendar()
    mentorCalendar.id = this.calendarId
    mentorCalendar.mentorId = this.user.id
    mentorCalendar.startDate = this.format(this.bsRangeValue[0], 'yyyy/MM/dd HH:mm:ss')
    mentorCalendar.endDate = this.format(this.bsRangeValue[1], 'yyyy/MM/dd HH:mm:ss')
    console.log(mentorCalendar)
    if (this.calendarId != null) {
      this.http.put<any>('/api/calendar/update/',
        mentorCalendar,
        { headers: this.headers, reportProgress: true })
        .subscribe((data: any) => {
          console.log('/api/calendar/update', data)
          if (data.status == 'success') {
            alert('update calendar successfully')
            setTimeout(() => {
              window.location.assign('/editskills')
            }, 1000)
          } else {
            alert('update calendar error')
          }
        })
    } else {
      this.http.post<any>('/api/calendar/add/',
        mentorCalendar,
        { headers: this.headers, reportProgress: true })
        .subscribe((data: any) => {
          console.log('/api/calendar/add', data)
          if (data == 'CREATED') {
            alert('add calendar successfully')
            setTimeout(() => {
              window.location.assign('/editskills')
            }, 1000)
          } else {
            alert('add calendar error')
          }
        })
    }

  }

  openModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template);
  }
  add(): void {
    this.action = 'add'
  }

  save(): any {
    let mentorId = this.user.id
    console.log(this.user.id)
    console.log(this.selectedOptions)
    let mentorSkillsList: MentorSkills[] = []
    this.selectedOptions.forEach(function (data, index) {
      // console.log(data)
      // console.log(index)
      let mentorSkills = new MentorSkills()
      mentorSkills.mentorId = mentorId
      mentorSkills.technologyId = data.id
      console.log(mentorSkills)
      mentorSkillsList.push(mentorSkills)
    });
    this.http.post<any>('/api/skills/multiAdd',
      mentorSkillsList,
      { headers: this.headers, reportProgress: true })
      .subscribe((data: any) => {
        console.log('/api/skills/add', data)
        if (data == 'CREATED') {
          alert(this.action + ' mentor skills successfully')
          this.action = 'saved'
          // setTimeout(() => {
          //   window.location.assign('/editskills')
          // }, 1000);
        } else {
          alert('add mentor skills error')
        }
      })
  }
  delete(id: number): any {
    console.log('/api/skills/deleteByTechId/', id)
    var index = this.selectedOptions.findIndex(function (v) {
      return id === v.id;
    })
    this.selectedOptions.splice(index, 1);
    this.http.delete('/api/skills/deleteByTechId/' + this.user.id + '/' + id)
      .subscribe((data: any) => {
        console.log('/api/skills/deleteByTechId/', data)
        if (data.status == 'success') {
          alert('delete skill successfully')
          // setTimeout(() => {
          //   window.location.assign('/editskills')
          // }, 1000);
        } else {
          alert('update skill error')
        }
      })
  }

  selectedValue: string
  selectedOption: any
  selectedOptions: any[] = []
  technologies: Technologiy[] = []

  change(event: any): void {
    console.log('change')
    this.alerts = []
  }
  onSelect(event: TypeaheadMatch): void {
    var index = this.selectedOptions.findIndex(function (v) {
      return event.item.id === v.id;
    })
    if (index < 0) {
      this.selectedOption = event.item
      this.selectedOptions.push(event.item)
      this.skillsArray.push(event.item.name)
      this.skills = this.skillsArray.toString()
      console.log(this.skills)
      console.log(this.selectedOptions)
    } else {
      this.alerts = [
        {
          type: 'danger',
          msg: `<strong>Warning!</strong> You have selected this skill.`
        }
      ]
    }
  }
}
